package fun.tan90.device.source.http.plugin.config;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Handler;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@RequiredArgsConstructor
public class VertxHttpServer extends AbstractVerticle {

    private final String name;

    private final String host;

    private final int port;

    private final String uri;

    private final String method;

    private final long bodyLimit;

    private final Handler<RoutingContext> requestHandler;

    private HttpServer httpServer;

    @Override
    public void start(Promise<Void> startPromise) {
        // 创建 HTTP 服务器
        this.httpServer = vertx.createHttpServer();

        // 创建路由器
        Router router = Router.router(vertx);

        // 解析请求体
        router.route().handler(BodyHandler.create().setBodyLimit(bodyLimit));

        // 全局日志中间件
        router.route().handler(ctx -> {
            log.info("{} {} ", ctx.request().method(), ctx.request().path());
            ctx.next();
        });

        router.route(HttpMethod.valueOf(method.toUpperCase()), uri).handler(requestHandler);

        // 启动服务器
        httpServer.requestHandler(router)
                .listen(port, host, event -> {
                    if (event.succeeded()) {
                        startPromise.complete();
                    } else {
                        startPromise.fail(event.cause());
                    }
                });
    }

    @Override
    public void stop(Promise<Void> stopPromise) {
        httpServer.close(event -> {
            if (event.succeeded()) {
                log.info("【{}】 HTTP 服务器已关闭 【http://{}:{}{}】", name,host, port, uri);
                stopPromise.complete();
            } else {
                stopPromise.fail(event.cause());
            }
        });
    }
}